package cn.lww.itrip.trade.controller;

import cn.lww.itrip.trade.config.WXPayConstants;
import cn.lww.itrip.trade.config.WXPayRequest;
import cn.lww.itrip.trade.config.WXPayUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/wx")
public class WxPayController {

        @RequestMapping("/qrcode")
        public   String  test(){

            return  "qrcode";
        }

    /**
     * 根据订单号创建订单
     * @param orderNo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createOrder/{orderNo}",method = RequestMethod.GET)
    public  String createOrder(@PathVariable String orderNo){
                try{

                    Map<String,String> map=new HashMap<String,String>();
                    map.put("appid","wxab8acb865bb1637e");
                    map.put("mch_id","11473623");
                    map.put("sign","");
                    map.put("nonce_str", WXPayUtil.generateNonceStr());
                    map.put("body","I旅行支付");
                    map.put("out_trade_no",orderNo);
                    map.put("total_fee","1");
                    map.put("spbill_create_ip","127.0.0.1");
                    map.put("notify_url","http://5jqhx2.natappfree.cc/trade/wx/notify");
                    map.put("trade_type","NATIVE");
                    String requestXml = WXPayUtil.generateSignedXml(map, "2ab9071b06b9f739b950ddb41db2690d", WXPayConstants.SignType.MD5);
                    String responesXml = WXPayRequest.requestOnce("https://api.mch.weixin.qq.com/pay/unifiedorder",requestXml.trim());
                    Map<String, String> map1 = WXPayUtil.xmlToMap(responesXml);
                if(map1.get("return_code").equals("SUCCESS")
                &&map1.get("return_code").equals("SUCCESS")){
                      String code_url=map1.get("code_url");
                  System.out.println(code_url);

                    return code_url;
        }
                }catch (Exception e){
                    e.printStackTrace();
                }

            return "";
        }

        //微信回调通知
    @RequestMapping("/notify")
    public   void  notifyUrl(HttpServletRequest request, HttpServletResponse response) {
        try {
            InputStream inputStream = request.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            StringBuffer sb = new StringBuffer();
            String temp;

            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            inputStream.close();

            Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
                //验签
            boolean flag = WXPayUtil.isSignatureValid(map, "2ab9071b06b9f739b950ddb41db2690d", WXPayConstants.SignType.MD5);

            if (flag) {
                if (map.get("return_code").equals("SUCCESS")
                        && map.get("return_code").equals("SUCCESS")) {

                    String out_trade_no = map.get("out_trade_no");
                    String prepay_id = map.get("prepay_id");


                    Map<String, String> responseMap = new HashMap<String, String>();

                    responseMap.put("return_code", "SUCCESS");
                    responseMap.put("return_msg", "处理成功");
                    String s = WXPayUtil.mapToXml(responseMap);

                    String responseXml = WXPayUtil.generateSignedXml(responseMap,
                            "2ab9071b06b9f739b950ddb41db2690d", WXPayConstants.SignType.MD5);
                    System.out.println("支付成功");
                    response.getWriter().write(responseXml);
                    response.getWriter().flush();
                }
            }
            }catch(Exception e){
                e.printStackTrace();
            }


        }

    /**
     * 微信支付成功后跳转页面
     */
@RequestMapping("/queryOrderStatus")
        public String queryOrderStatus() {

    return "true";
}
}



